<?php

namespace app\home\controller;

use app\home\model\Member;
use app\home\validate\LoginValidate;
use think\Cache;
use think\Controller;
use think\Request;



//home/login/login
class Login extends Controller
{

	protected $url;
	protected $appId;
	protected $secret;

	public function __construct (Request $request = null) {
		parent::__construct($request);
		$this->url = config('wxinfo.loginUrl');
		$this->secret = config('wxinfo.secret');
		$this->appId = config('wxinfo.appId');
	}

	public function login(){

		$validate = new LoginValidate();

		$validateRes = $validate->goSceneCheck('login');

		if($validateRes){
			return error($validateRes);
		}

		$code = $this->request->param('code');

		$url = sprintf($this->url,$this->appId,$this->secret,$code);

		$result = json_decode(https_request($url),true);

		if(array_key_exists('errcode',$result) && $result['errcode'] !=0){
			return error($result['errmsg'],$result['errcode']);
		}

		$memberModel = new Member();

		$member = $memberModel->where(['openid'=>$result['openid']])->find();

		if(empty($member)){//新用户插入数据
			$memberModel->openid = $result['openid'];
			$memberModel->createtime = time();
			$memberModel->save();
			$member_id = $memberModel->id;
		}else{
			$member_id = $member->id;
		}

		$token = md5(time().$member_id);

		Cache::set($token,['member_id'=>$member_id,'session_key'=>$result['session_key']],7200);

		return success(['token'=>$token,'session_key'=>$result['session_key']]);

	}
}
